<template>
  <div class="login-report">
    <!-- 页面标题 -->
    <div class="report-header">
      <h2 class="page-title">登录统计报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-button type="success" icon="Download" @click="handleExport">
          导出报表
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon primary">
            <el-icon><Connection /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.totalLogins || 0 }}</div>
            <div class="card-label">总登录次数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon success">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.successLogins || 0 }}</div>
            <div class="card-label">成功登录</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon danger">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.failedLogins || 0 }}</div>
            <div class="card-label">失败登录</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6" :xs="12">
        <div class="overview-card">
          <div class="card-icon warning">
            <el-icon><User /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-number">{{ overview.uniqueUsers || 0 }}</div>
            <div class="card-label">独立用户</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 登录趋势图 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>登录趋势分析</span>
              <el-radio-group v-model="trendType" size="small" @change="handleTrendTypeChange">
                <el-radio-button label="day">按天</el-radio-button>
                <el-radio-button label="hour">按小时</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="loginTrendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 登录成功率 -->
      <el-col :span="12" :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>登录成功率</span>
            </div>
          </template>
          <div ref="successRateChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细分析 -->
    <el-row :gutter="20" class="detail-row">
      <!-- 登录地域分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>登录地域分布</span>
            </div>
          </template>
          <div ref="locationChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 浏览器分布 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>浏览器分布</span>
            </div>
          </template>
          <div ref="browserChartRef" class="chart-container-small"></div>
        </el-card>
      </el-col>

      <!-- 异常登录记录 -->
      <el-col :span="8" :xs="24">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>异常登录记录</span>
            </div>
          </template>
          <div class="exception-list">
            <div v-for="(item, index) in exceptionLogins" :key="index" class="exception-item">
              <div class="exception-user">{{ item.userName }}</div>
              <div class="exception-ip">{{ item.ipaddr }}</div>
              <div class="exception-time">{{ item.time }}</div>
              <el-tag type="danger" size="small">{{ item.reason }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>登录详细记录</span>
          <div class="table-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索用户/IP"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
            <el-select v-model="statusFilter" placeholder="状态" clearable style="width: 100px" @change="handleSearch">
              <el-option label="成功" value="0" />
              <el-option label="失败" value="1" />
            </el-select>
          </div>
        </div>
      </template>
      
      <el-table v-loading="tableLoading" :data="loginData" stripe>
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="ipaddr" label="登录IP" width="120" />
        <el-table-column prop="loginLocation" label="登录地点" width="120" />
        <el-table-column prop="browser" label="浏览器" width="120" />
        <el-table-column prop="os" label="操作系统" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="msg" label="提示消息" show-overflow-tooltip />
        <el-table-column prop="loginTime" label="登录时间" width="160" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getLoginData"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getLoginReport, exportLoginReport } from '@/api/report/login'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const dateRange = ref<string[]>([])
const trendType = ref('day')
const searchText = ref('')
const statusFilter = ref('')
const tableLoading = ref(false)
const total = ref(0)

// 概览数据
const overview = reactive({
  totalLogins: 0,
  successLogins: 0,
  failedLogins: 0,
  uniqueUsers: 0,
})

// 异常登录数据
const exceptionLogins = ref<any[]>([])

// 登录数据
const loginData = ref<any[]>([])

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  startDate: '',
  endDate: '',
  userName: '',
  status: '',
})

// 图表引用
const loginTrendChartRef = ref()
const successRateChartRef = ref()
const locationChartRef = ref()
const browserChartRef = ref()

// 图表实例
let loginTrendChart: echarts.ECharts
let successRateChart: echarts.ECharts
let locationChart: echarts.ECharts
let browserChart: echarts.ECharts

// 获取报表数据
const getReportData = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
      trendType: trendType.value,
    }
    
    // 模拟数据
    const mockData = {
      overview: {
        totalLogins: 1856,
        successLogins: 1679,
        failedLogins: 177,
        uniqueUsers: 245,
      },
      trendData: generateMockTrendData(),
      locationData: [
        { name: '北京', value: 520 },
        { name: '上海', value: 320 },
        { name: '广州', value: 280 },
        { name: '深圳', value: 240 },
        { name: '其他', value: 496 },
      ],
      browserData: [
        { name: 'Chrome', value: 856 },
        { name: 'Firefox', value: 324 },
        { name: 'Safari', value: 280 },
        { name: 'Edge', value: 240 },
        { name: '其他', value: 156 },
      ],
    }
    
    // 更新概览数据
    Object.assign(overview, mockData.overview)
    
    // 渲染图表
    nextTick(() => {
      renderLoginTrendChart(mockData.trendData)
      renderSuccessRateChart()
      renderLocationChart(mockData.locationData)
      renderBrowserChart(mockData.browserData)
    })
  } catch (error) {
    console.error('获取登录报表数据失败:', error)
    ElMessage.error('获取登录报表数据失败')
  }
}

// 获取登录数据表格
const getLoginData = async () => {
  tableLoading.value = true
  try {
    // 模拟数据
    loginData.value = generateMockLoginData()
    total.value = 50
  } catch (error) {
    console.error('获取登录数据失败:', error)
  } finally {
    tableLoading.value = false
  }
}

// 渲染登录趋势图表
const renderLoginTrendChart = (data: any[]) => {
  if (!loginTrendChartRef.value) return
  
  if (!loginTrendChart) {
    loginTrendChart = echarts.init(loginTrendChartRef.value)
  }
  
  const times = data.map(item => item.time)
  const successCounts = data.map(item => item.success)
  const failCounts = data.map(item => item.fail)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['成功登录', '失败登录']
    },
    xAxis: {
      type: 'category',
      data: times
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成功登录',
        type: 'line',
        data: successCounts,
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '失败登录',
        type: 'line',
        data: failCounts,
        itemStyle: { color: '#F56C6C' }
      }
    ]
  }
  
  loginTrendChart.setOption(option)
}

// 渲染成功率图表
const renderSuccessRateChart = () => {
  if (!successRateChartRef.value) return
  
  if (!successRateChart) {
    successRateChart = echarts.init(successRateChartRef.value)
  }
  
  const successRate = (overview.successLogins / overview.totalLogins * 100).toFixed(1)
  
  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        center: ['50%', '75%'],
        radius: '90%',
        min: 0,
        max: 100,
        splitNumber: 8,
        axisLine: {
          lineStyle: {
            width: 6,
            color: [
              [0.25, '#FF6E76'],
              [0.5, '#FDDD60'],
              [0.75, '#58D9F9'],
              [1, '#7CFFB2']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 20,
          offsetCenter: [0, '-60%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          length: 12,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        splitLine: {
          length: 20,
          lineStyle: {
            color: 'auto',
            width: 5
          }
        },
        axisLabel: {
          color: '#464646',
          fontSize: 20,
          distance: -60,
          formatter: function (value: number) {
            return value + '%'
          }
        },
        title: {
          offsetCenter: [0, '-20%'],
          fontSize: 20
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '-35%'],
          valueAnimation: true,
          formatter: function (value: number) {
            return Math.round(value) + '%'
          },
          color: 'auto'
        },
        data: [
          {
            value: parseFloat(successRate),
            name: '登录成功率'
          }
        ]
      }
    ]
  }
  
  successRateChart.setOption(option)
}

// 渲染地域分布图表
const renderLocationChart = (data: any[]) => {
  if (!locationChartRef.value) return
  
  if (!locationChart) {
    locationChart = echarts.init(locationChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        data: data,
        label: {
          fontSize: 12
        }
      }
    ]
  }
  
  locationChart.setOption(option)
}

// 渲染浏览器分布图表
const renderBrowserChart = (data: any[]) => {
  if (!browserChartRef.value) return
  
  if (!browserChart) {
    browserChart = echarts.init(browserChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        data: data,
        label: {
          fontSize: 12
        }
      }
    ]
  }
  
  browserChart.setOption(option)
}

// 生成模拟趋势数据
const generateMockTrendData = () => {
  const data = []
  const today = new Date()
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today.getTime() - i * 24 * 60 * 60 * 1000)
    data.push({
      time: date.toISOString().split('T')[0],
      success: Math.floor(Math.random() * 200) + 100,
      fail: Math.floor(Math.random() * 50) + 10,
    })
  }
  
  return data
}

// 生成模拟登录数据
const generateMockLoginData = () => {
  const mockData = []
  const users = ['admin', 'test', 'user1', 'user2', 'manager']
  const browsers = ['Chrome', 'Firefox', 'Safari', 'Edge']
  const locations = ['北京', '上海', '广州', '深圳', '杭州']
  
  for (let i = 0; i < 10; i++) {
    mockData.push({
      userName: users[i % users.length],
      ipaddr: `192.168.1.${100 + i}`,
      loginLocation: locations[i % locations.length],
      browser: browsers[i % browsers.length],
      os: 'Windows 10',
      status: Math.random() > 0.2 ? '0' : '1',
      msg: Math.random() > 0.2 ? '登录成功' : '密码错误',
      loginTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString(),
    })
  }
  
  return mockData
}

// 日期范围变化
const handleDateChange = () => {
  refreshData()
}

// 趋势类型变化
const handleTrendTypeChange = () => {
  getReportData()
}

// 搜索
const handleSearch = () => {
  queryForm.userName = searchText.value
  queryForm.status = statusFilter.value
  queryForm.pageNum = 1
  getLoginData()
}

// 刷新数据
const refreshData = () => {
  getReportData()
  getLoginData()
}

// 导出报表
const handleExport = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || '',
      endDate: dateRange.value?.[1] || '',
    }
    
    ElMessage.success('报表导出成功')
  } catch (error) {
    ElMessage.error('报表导出失败')
  }
}

// 初始化异常登录数据
const initExceptionLogins = () => {
  exceptionLogins.value = [
    { userName: 'admin', ipaddr: '192.168.1.100', time: '10:30', reason: '多次失败' },
    { userName: 'test', ipaddr: '192.168.1.101', time: '09:45', reason: '异常IP' },
    { userName: 'user1', ipaddr: '192.168.1.102', time: '08:20', reason: '频繁登录' },
  ]
}

// 初始化
onMounted(() => {
  // 设置默认日期范围（最近7天）
  const today = new Date()
  const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  dateRange.value = [
    lastWeek.toISOString().split('T')[0],
    today.toISOString().split('T')[0]
  ]
  
  refreshData()
  initExceptionLogins()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    loginTrendChart?.resize()
    successRateChart?.resize()
    locationChart?.resize()
    browserChart?.resize()
  })
})
</script>

<style lang="scss" scoped>
.login-report {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.overview-row,
.charts-row,
.detail-row {
  margin-bottom: 20px;
}

.overview-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    .el-icon {
      font-size: 24px;
      color: white;
    }
    
    &.primary {
      background: linear-gradient(135deg, #409EFF, #6BB7FF);
    }
    
    &.success {
      background: linear-gradient(135deg, #67C23A, #95D475);
    }
    
    &.warning {
      background: linear-gradient(135deg, #E6A23C, #F0C674);
    }
    
    &.danger {
      background: linear-gradient(135deg, #F56C6C, #FF8A95);
    }
  }
  
  .card-content {
    .card-number {
      font-size: 28px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 5px;
    }
    
    .card-label {
      font-size: 14px;
      color: #606266;
    }
  }
}

.chart-card,
.detail-card,
.table-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  
  .table-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.chart-container {
  width: 100%;
  height: 300px;
}

.chart-container-small {
  width: 100%;
  height: 250px;
}

.exception-list {
  .exception-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .exception-user {
      font-weight: 500;
      color: #303133;
    }
    
    .exception-ip {
      color: #606266;
      font-size: 12px;
    }
    
    .exception-time {
      color: #909399;
      font-size: 12px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-report {
    padding: 10px;
  }
  
  .report-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
    
    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }
  
  .overview-card {
    padding: 15px;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container-small {
    height: 200px;
  }
}
</style>

